﻿using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AuthenticationAPI.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using AuthenticationAPI.Models.DbContext;
using System.Collections.Generic;
using AuthenticationAPI.Models.Utility;

namespace AuthenticationAPI.Controllers
{
    public class FavoriteProjectController : ApiController
    {
        [Route("api/User/{userName}/FavoriteProject")]
        [HttpGet]
        public HttpResponseMessage GetFavoriteProject(string userName)
        {
            using (var db = new AuthenticationEntities())
            {
                var list = db.FavoriteProject.Where(p => p.UserName == userName).Select(p => p.PrjId).ToList();
                return Request.CreateResponse(HttpStatusCode.OK, list);
            }
        }

        [Route("api/User/{userName}/FavoriteProject")]
        [HttpPost]
        public HttpResponseMessage SaveFavoriteProject(string userName, [FromBody]int prjId)
        {
            using (var db = new AuthenticationEntities())
            {
                var id = db.FavoriteProject.SingleOrDefault(p => p.UserName == userName && p.PrjId == prjId);
                if (id == null)
                {
                    var favorPrj = new FavoriteProject()
                    {
                        PrjId = prjId,
                        UserName = userName
                    };
                    db.FavoriteProject.Add(favorPrj);
                    db.SaveChanges();
                }
                return Request.CreateResponse(HttpStatusCode.OK);
            }
        }
    }
}
